package com.copa.utils;

import com.copa.entity.Music;

import java.io.IOException;
import java.util.List;
import java.util.function.Function;

import static com.copa.provider.music.netease.NeteaseMusicApi.getSongIdsFromSongList;

public class SongUtils {
    /**
     * 使用api做一次请求，批量填入歌曲列表每一首歌曲的url
     *
     * @param songs
     * @throws IOException
     */
    public static void fillSongLinks(List<Music> songs, Function<String[], List<Music>>
            function) {
        if (songs != null && !songs.isEmpty()) {
            // 1. 先获得所有songId组成的列表
            String[] songIds = getSongIdsFromSongList(songs);
            // 2. 使用api批量获取歌曲url
            List<Music> links = function.apply(songIds);
            // 3. 将对应的url插入到music
            for (int i = 0; i < songs.size(); i++) {
                for (int j = 0; j < links.size(); j++) {
                    if (songs.get(i).getJumpUrl().substring(songs.get(i).getJumpUrl().indexOf("id=") + 3)
                            .equals(links.get(j).getBrief())) {
                        songs.get(i).setMusicUrl(links.get(j).getMusicUrl());
                    }
                }
            }
        }
    }

    @SuppressWarnings("unused")
    public static String getReadableBitRate(long bitRate) {
        //noinspection SpellCheckingInspection
        if (bitRate <= 0) {
            return "";
        } else {
            return (bitRate / 1000) + "kbps";
        }
    }
}
